<?php
/**
 * @copyright: ©2024 永州 微聚商网络科技有限公司
 * @link: https://www.wEijuyunke.com
 */
namespace app\mobile\controller;

use app\admin\model\ClipProject;
use app\admin\model\ClipResource;
use app\admin\model\ClipVideoRepost;
use app\admin\model\FigureAiTitle;
use app\admin\model\RepostComment;
use app\admin\model\ScanTask;
use app\admin\model\ScanTaskTitle;
use app\admin\model\ScanTaskVideo;
use app\api\controller\figure\DyUser;
use app\BaseController;
use app\common\service\KuaishouService;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigureUser;
use app\admin\model\FigureVideo;
use app\admin\model\FigureFaceSwapTask;
use app\common\service\ApiService;
use FFMpeg\FFMpeg;
use app\admin\service\TriggerService;
use app\admin\model\SystemConfig;
use app\admin\model\FigureDyUser;
use app\admin\model\FigureKsUser;
use app\admin\model\FigureVideoRepost;
use app\admin\model\FigureRepostSet;

/**
 * 视频转发操作
 *
 * @author Administrator
 *        
 */
class Repost extends BaseController
{

    /**
     * 转发设置
     * http://aigc.weijuyunke.cn/mobile/repost/set
     */
    public function set()
    {
        $set = FigureRepostSet::where("id", 1)->find();
        
        if (empty($set)) {
            $set = [];
        }
        
        return result(0, 'success', $set);
    }

    /**
     * 转发视频
     * http://aigc.weijuyunke.cn/mobile/repost/videoExhibit
     *
     * @param
     *            way 1-dy 2-ks
     * @param
     *            uid 用户id
     * @param
     *            video_id 视频id
     * @param
     *            type 1-视频合成 2-视频换脸
     */
    public function videoExhibit()
    {
        try {
            $way = input('way');
            $uid = input('uid');
            $video_id = input('video_id');
            $type = input('type');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            if ($type == 1) {
                $video = FigureVideo::where([
                    'uid' => $uid,
                    'id' => $video_id
                ])->find();
            } elseif ($type == 2) {
                $video = FigureFaceSwapTask::where([
                    'uid' => $uid,
                    'id' => $video_id
                ])->find();
            }
            
            if (empty($video)) {
                return result(- 1, '视频不存在');
            }
            
            if ($way == 1 && ! empty($video['dy_qrcode'])) {
                return result(0, 'success', $video['dy_qrcode']);
            }
            if ($way == 2 && ! empty($video['ks_qrcode'])) {
                return result(0, 'success', $video['ks_qrcode']);
            }
            
            $douyin_set = sysconfig('forward');
            $domain = request()->domain();
            
            if ($way == 1) {
                $url = $domain . "/mobile/index/dy_index?video_id=" . $video_id . "#/?type={$type}&video_id=" . $video_id;
            } elseif ($way == 2) {
                $redirect_uri = urlencode($domain . "/mobile/repost/ksUserAuth?type={$type}&video_id=" . $video_id);
                $url = "https://open.kuaishou.com/oauth2/authorize?app_id=" . $douyin_set['k_appid'] . "&response_type=code&scope=user_info,user_video_publish,user_video_info&redirect_uri=" . $redirect_uri;
            }
            
            $qrcode = common_qr_code($url, 'repost');
            
            if ($way == 1) {
                $video->save([
                    'dy_qrcode' => $qrcode
                ]);
            } elseif ($way == 2) {
                $video->save([
                    'ks_qrcode' => $qrcode
                ]);
            }
            
            return result(0, 'success', $qrcode);
        } catch (\Exception $e) {
            Log::write("videoExhibit 失败" . json_encode($e->getTrace()), 'info');
            return result(- 1, '操作异常:' . $e->getMessage(), $e->getTrace());
        }
    }

    /**
     * KS用户授权
     * http://aigc.weijuyunke.cn/mobile/repost/ksUserAuth
     *
     * @param
     *            code
     */
    public function ksUserAuth()
    {
        try {
            $type = input('type');
            $video_id = input('video_id');
            $code = input('code');

            $task_id = input('task_id');

            $forwardSet = sysconfig('forward');
            
            $k_appid = $forwardSet['k_appid'];
            $k_secret = $forwardSet['k_secret'];
            
            $url = "https://open.kuaishou.com/oauth2/access_token?app_id=" . $k_appid . "&app_secret=" . $k_secret . "&code=" . $code . "&grant_type=authorization_code";
            $obj = httpGet($url);
            $data = json_decode($obj, true);
            
            if ($data['result'] == 1) {
                $user_url = "https://open.kuaishou.com/openapi/user_info?app_id=" . $k_appid . "&access_token=" . $data['access_token'];
                $user_info = httpGet($user_url);
                $user_data = json_decode($user_info, true);
                $user = Db::table('wjyk_figure_ks_user')->where('openid', $data['open_id'])->find();
                $arr = array(
                    'nickname' => $user_data['user_info']['name'],
                    'openid' => $data['open_id'],
                    'avatar' => $user_data['user_info']['head'],
                    'access_token' => $data['access_token'],
                    'expires_in' => $data['expires_in'] + time(),
                    'refresh_token' => $data['refresh_token'],
                    'city' => $user_data['user_info']['city']
                );
                
                if ($user) {
                    FigureKsUser::where('id', $user['id'])->save($arr);
                    $uid = $user['id'];
                } else {
                    $arr['create_time'] = time();
                    $uid = FigureKsUser::insertGetId($arr);
                }
                if ($task_id){
                    header('Location:' . request()->domain() . "/mobile/index/ks_index?task_id=" . $task_id . "#/?uid=" . $uid . "&type=" .$type . "&task_id=" . $task_id. "&qrcode_type=" . 2);

                }else{
                    header('Location:' . request()->domain() . "/mobile/index/ks_index?video_id=" . $video_id . "#/?uid=" . $uid . "&type=" .$type . "&video_id=" . $video_id);

                }

            } else {
                return result(- 1, $data['error_msg']);
            }
        } catch (\Exception $e) {
            Log::write("ksUserAuth 失败" . json_encode($e->getTrace()), 'info');
            return result(- 1, '操作异常:' . $e->getMessage(), $e->getTrace());
        }
    }

    /**
     * KS转发
     * http://aigc.weijuyunke.cn/mobile/repost/ksIssue
     *
     * @param
     *            uid KS用户id
     * @param
     *            type 1-视频合成 2-视频换脸
     * @param
     *            video_id 视频id
     */
    public function ksIssue()
    {
        $uid = input('uid');
        $type = input('type');
        $video_id = input('video_id');
        
        $user = FigureKsUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(- 1, '用户不存在');
        }
        
        if ($type == 1) {
            $video = FigureVideo::where('id', $video_id)->find();
        } elseif ($type == 2) {
            $video = FigureFaceSwapTask::where('id', $video_id)->find();
        }
        
        if (empty($video)) {
            return result(- 1, '视频不存在');
        }
        
        $file = $video['local_url'];
        $cover = $video['local_cover'];
        $name = $video['name'];
        
        $kuaishou_set = sysconfig('forward');
        
        $url = "https://open.kuaishou.com/openapi/photo/start_upload?app_id=" . $kuaishou_set['k_appid'] . "&access_token=" . $user['access_token'];
        $arr = wtw_request($url, "{}");
        $arr1 = json_decode($arr, true);
        
        if ($arr1['result'] == 1) {
            $upload_token = $arr1['upload_token'];
            $endpoint = $arr1['endpoint'];
            $upload_url = "http://{$endpoint}/api/upload?upload_token=" . $upload_token;
            $reply = http_binary($file, $upload_url);
            
            $data = json_decode($reply, true);
            if ($data['result'] == 1) {
                $publish_url = "https://open.kuaishou.com/openapi/photo/publish?access_token=" . $user['access_token'] . "&app_id=" . $kuaishou_set['k_appid'] . "&upload_token=" . $upload_token;
                $send_data = array(
                    'cover' => $cover,
                    'caption' => $name
                );
                $arr2 = wtw_request($publish_url, $send_data);
                $arr3 = json_decode($arr2, true);
                if ($arr3['result'] == 1) {
                    
                    Db::table('wjyk_figure_video_repost')->insert(array(
                        'uid' => $video['uid'],
                        'video_id' => $video_id,
                        'way' => 2,
                        'type' => $type,
                        'video_url' => $file,
                        'video_cover' => $cover,
                        'k_uid' => $uid,
                        'd_uid' => 0,
                        'name' => $name,
                        'is_repost' => 1,
                        'photo_id' => $arr3['video_info']['photo_id'],
                        'create_time' => time()
                    ));
                    
                    return result(0, '发布视频成功');
                } else {
                    return result(- 1, '发布视频失败', $arr3);
                }
            }
            return result(- 1, '上传视频失败');
        } else {
            return result(- 1, '获取上传权限失败');
        }
    }

    /**
     * 获取DY配置参数
     * http://aigc.weijuyunke.cn/mobile/repost/dySignature
     *
     * @param
     *            url
     */
    public function dySignature()
    {
        $douyin_set = sysconfig('forward');
        
        $client_key = $douyin_set['d_key'];
        $client_secret = $douyin_set['d_secret'];
        $jsb_ticket = $douyin_set['d_jsb_ticket'];
        $jsb_ticket_expires_in = $douyin_set['d_jsb_ticket'];
        
        $t = time();
        
        $client_url = "https://open.douyin.com/oauth/client_token/?grant_type=client_credential&client_key=" . $client_key . "&client_secret=" . $client_secret;
        
        $post_data = array(
            'grant_type' => 'client_credential',
            'client_key' => $client_key,
            'client_secret' => $client_secret
        );
        $client_obj = wtw_request($client_url, $post_data);
        $client_data = json_decode($client_obj, true);
        
        if (isset($client_data['data']['error_code']) && ! empty($client_data['data']['error_code'])) {
            
            return result(- 1, 'client--->' . $client_data['data']['description']);
            exit();
        }
        
        $access_token = $client_data['data']['access_token'];
        $expires_in = $client_data['data']['expires_in'] + $t;
        
        SystemConfig::where('name', 'd_access_token')->update([
            'value' => $access_token
        ]);
        
        SystemConfig::where('name', 'd_expires_in')->update([
            'value' => $expires_in
        ]);
        
        TriggerService::updateSysconfig();
        
        if ($t > $jsb_ticket_expires_in) {
            
            $ticket_url = "https://open.douyin.com/js/getticket/";
            
            $ticket_obj = headerGet($ticket_url, array(
                'access-token: ' . $access_token
            ));
            $ticket_data = json_decode($ticket_obj, true);
            
            if (isset($ticket_data['data']['error_code']) && ! empty($ticket_data['data']['error_code'])) {
                
                return result(- 1, 'ticket--->' . $ticket_data['data']['description']);
                exit();
            }
            
            if ($ticket_data) {
                
                $jsb_ticket = $ticket_data['data']['ticket'];
                $jsb_ticket_expires_in = $ticket_data['data']['expires_in'] + $t;
                
                SystemConfig::where('name', 'd_jsb_ticket')->update([
                    'value' => $jsb_ticket
                ]);
                
                SystemConfig::where('name', 'd_jsb_ticket_expires_in')->update([
                    'value' => $jsb_ticket_expires_in
                ]);
                
                TriggerService::updateSysconfig();
            }
        }
        
        $url = input('url');
        $qrcode_type= input('qrcode_type');
        $nonce_str = createNonceStr();
        $time = (string) time();
        $param = [
            "nonce_str" => $nonce_str,
            "jsapi_ticket" => $jsb_ticket,
            "timestamp" => $time,
            "url" => $url,
            'qrcode_type' => $qrcode_type
        ];
        
        ksort($param);
        
        $string = ToUrlParams($param);
        $signature = md5($string);
        
        $result = array(
            "client_key" => $client_key,
            "nonce_str" => $nonce_str,
            "timestamp" => $time,
            "signature" => $signature,
            "url" => $url
        );
        
        return result(0, 'success', $result);
    }

    /**
     * DY用户授权
     * http://aigc.weijuyunke.cn/mobile/repost/dyUserAuth
     *
     * @param
     *            code
     */
    public function dyUserAuth()
    {
        $code = input('code');
        
        $douyin_set = sysconfig('forward');


        
        $client_key = $douyin_set['d_key'];
        $client_secret = $douyin_set['d_secret'];
        
        $url = "https://open.douyin.com/oauth/access_token/?client_key=" . $client_key . "&client_secret=" . $client_secret . "&code=" . $code . "&grant_type=authorization_code";


        $obj = httpGet($url);
        $data = json_decode($obj, true);
        
        if (isset($data['data']['error_code']) && $data['data']['error_code'] == 0) {
            
            $user_url = "https://open.douyin.com/oauth/userinfo/?open_id=" . $data['data']['open_id'] . "&access_token=" . $data['data']['access_token'];
            $user_info = httpGet($user_url);
            $user_data = json_decode($user_info, true);
            
            $telphone = '';
            
            if (! empty($user_data['data']['encrypt_mobile'])) {
                $encrypted_mobile = $user_data['data']['encrypt_mobile'];
                if (! empty($encrypted_mobile)) {
                    $telphone = empty(decrypt($encrypted_mobile, $client_secret)) ? '' : decrypt($encrypted_mobile, $client_secret);
                }
            }
            
            $user = Db::table('wjyk_figure_dy_user')->where('openid', $data['data']['open_id'])->find();
            
            $arr = array(
                'nickname' => $user_data['data']['nickname'],
                'openid' => $data['data']['open_id'],
                'avatar' => $user_data['data']['avatar'],
                'access_token' => $data['data']['access_token'],
                'expires_in' => time() + $data['data']['expires_in'],
                'refresh_expires_in' => time() + $data['data']['refresh_expires_in'],
                'refresh_token' => $data['data']['refresh_token'],
                'telphone' => $telphone
            );
            if ($user) {
                FigureDyUser::where('id', $user['id'])->save($arr);
                $uid = $user['id'];
            } else {
                $arr['create_time'] = time();
                $uid = FigureDyUser::insertGetId($arr);
            }
            
            return result(0, 'success', $uid);
        } else {
            return result(- 1, $data['data']['description']);
        }
    }

    /**
     * DY转发
     * http://aigc.weijuyunke.cn/mobile/repost/dyIssue
     *
     * @param
     *            uid DY用户id
     * @param
     *            type 1-视频合成 2-视频换脸
     * @param
     *            video_id 视频id
     */
    public function dyIssue()
    {
        $uid = input('uid');
        $type = input('type');
        $video_id = input('video_id');
        
        $user = FigureDyUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(- 1, '用户不存在');
        }
        
        if ($type == 1) {
            $video = FigureVideo::where('id', $video_id)->find();
        } elseif ($type == 2) {
            $video = FigureFaceSwapTask::where('id', $video_id)->find();
        }
        if (empty($video)) {
            return result(- 1, '视频不存在');
        }
        $video = FigureVideo::where('id', $video_id)->find();
        if (empty($video)) {
            return result(- 1, '视频不存在');
        }
        
        $file = $video['local_url'];
        $cover = $video['local_cover'];
        $name = $video['name'];
        
        $douyin_set = sysconfig('forward');
        $client_key = $douyin_set['d_key'];
        $client_secret = $douyin_set['d_secret'];
        
        $client_url = "https://open.douyin.com/oauth/client_token/?grant_type=client_credential&client_key=" . $client_key . "&client_secret=" . $client_secret;
        $client_obj = httpGet($client_url);
        $client_data = json_decode($client_obj, true);
        
        if ($client_data) {
            $access_token = $client_data['data']['access_token'];
            
            $ticket_client_url = "https://open.douyin.com/open/getticket/";
            $ticket_client_obj = share_wtw_request($ticket_client_url, null, [
                'Content-Type: application/json; charset=utf-8',
                'access-token: ' . $access_token
            ]);
            
            $ticket_client_obj = \json_decode($ticket_client_obj, true);
            if ($ticket_client_obj && $ticket_client_obj['data']['error_code'] == 0) {
                // 去获取分享id
                
                $share_url = "https://open.douyin.com/share-id/?need_callback=true";
                $share_data = \json_decode(share_wtw_request($share_url, null, [
                    'Content-Type: application/json; charset=utf-8',
                    'access-token: ' . $access_token
                ]), true);
                
                $nonce_str = createNonceStr();
                $ticket = $ticket_client_obj['data']['ticket'];
                $time = (string) time();
                $param = [
                    "nonce_str" => $nonce_str,
                    "ticket" => $ticket,
                    "timestamp" => $time
                ];
                $share_id = "";
                if ($share_data && $share_data['data']['error_code'] == 0) {
                    $share_id = $share_data['data']['share_id'];
                } else {
                    return result(- 1, "分享id获取失败");
                    exit();
                }
                
                ksort($param);
                
                $string = ToUrlParams($param);
                $sign = md5($string);
                
                Db::table('wjyk_figure_video_repost')->insert(array(
                    'uid' => $video['uid'],
                    'video_id' => $video_id,
                    'way' => 1,
                    'type' => $type,
                    'd_uid' => $uid,
                    'k_uid' => 0,
                    'share_id' => $share_id,
                    'name' => $name,
                    'video_url' => $file,
                    'video_cover' => $cover,
                    'create_time' => time()
                ));
                
                $result = array(
                    "client_key" => $client_key,
                    "nonce_str" => $nonce_str,
                    "timestamp" => $time,
                    "sign" => $sign,
                    "state" => $share_id,
                    "share_type" => "h5",
                    "share_to_publish" => 1,
                    "video_path" => $file
                );
                return result(0, 'success', $result);
            } else {
                return result(- 1, $ticket_client_obj['data']['description']);
            }
        }
    }


    /**
     * 转发记录
     * http://aigc.weijuyunke.cn/mobile/repost/repostList
     *
     * @param
     *            uid 用户id
     * @param
     *            video_id 视频id
     * @param
     *            way 1-DY;2-KS
     * @param
     *            type 1-视频合成 2-视频换脸
     * @param
     *            year 年
     * @param
     *            month 月
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function repostList()
    {
        try {
            $uid = input('uid');
            $video_id = input('video_id');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            
            $where = " uid = {$uid} AND video_id = {$video_id} AND is_repost = 1 ";
            
            if (! empty(input('way'))) {
                $way = input('way');
                $where .= " AND way = '{$way}'";
            }
            
            if (! empty(input('type'))) {
                $type = input('type');
                $where .= " AND type = '{$type}'";
            }
            
            if (! empty(input('year'))) {
                $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y') = " . input('year');
                
                if (! empty(input('month'))) {
                    $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%m') = " . input('month');
                }
            }
            
            if (! empty(input('day'))) {
                $day = input('day');
                $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$day}'";
            }
            
            $total = FigureVideoRepost::where($where)->count();
            if ($total) {
                $list = FigureVideoRepost::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
                
                foreach ($list as $key => $value) {
                    
                    if ($value['way'] == 1) {
                        $user = FigureDyUser::where('id', $value['d_uid'])->find();
                    } elseif ($value['way'] == 2) {
                        $user = FigureKsUser::where('id', $value['k_uid'])->find();
                    }
                    
                    $list[$key]['nickname'] = isset($user['nickname']) ? $user['nickname'] : '';
                    $list[$key]['avatar'] = isset($user['avatar']) ? $user['avatar'] : '';
                }
            } else {
                $list = array();
            }
            
            $totalPage = ceil($total / $psize);
            
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 转发统计
     * http://aigc.weijuyunke.cn/mobile/repost/dataStatis
     *
     * @param
     *            uid 用户id
     * @param
     *            type 1-视频合成 2-视频换脸 非必传
     * @param
     *            video_id 视频id 非必传
     */
    public function dataStatis()
    {
        $uid = input('uid');
        
        $user = FigureUser::where('id', $uid)->find();
        
        if (empty($user)) {
            return result(- 1, '未找到用户');
        }
        
        $where = " uid = {$uid} ";
        
        if (! empty(input('type'))) {
            $type = input('type');
            $where .= " AND type = '{$type}'";
        }
        
        if (! empty(input('video_id'))) {
            $video_id = input('video_id');
            $where .= " AND video_id = '{$video_id}'";
        }
        
        $dyWhere = $where . " AND way = 1 ";
        
        $dy_comment = FigureVideoRepost::where($dyWhere)->sum('total_comment');
        $dy_like = FigureVideoRepost::where($dyWhere)->sum('total_like');
        $dy_play = FigureVideoRepost::where($dyWhere)->sum('total_play');
        $dy_share = FigureVideoRepost::where($dyWhere)->sum('total_share');
        
        $ksWhere = $where . " AND way = 2 ";
        
        $ks_comment = FigureVideoRepost::where($ksWhere)->sum('total_comment');
        $ks_like = FigureVideoRepost::where($ksWhere)->sum('total_like');
        $ks_play = FigureVideoRepost::where($ksWhere)->sum('total_play');
        $ks_share = FigureVideoRepost::where($ksWhere)->sum('total_share');
        
        $result['dy_comment'] = empty($dy_comment) ? 0 : $dy_comment;
        $result['dy_like'] = empty($dy_like) ? 0 : $dy_like;
        $result['dy_play'] = empty($dy_play) ? 0 : $dy_play;
        $result['dy_share'] = empty($dy_share) ? 0 : $dy_share;
        $result['ks_comment'] = empty($ks_comment) ? 0 : $ks_comment;
        $result['ks_like'] = empty($ks_like) ? 0 : $ks_like;
        $result['ks_play'] = empty($ks_play) ? 0 : $ks_play;
        $result['ks_share'] = empty($ks_share) ? 0 : $ks_share;
        
        return result(0, 'success', $result);
    }

    /**
     * 作品统计
     * http://aigc.weijuyunke.cn/mobile/repost/workStatis
     *
     * @param
     *            uid 用户id
     * @param
     *            year 年
     * @param
     *            month 月
     */
    public function workStatis()
    {
        $uid = input('uid');
        $year = input('year');
        $month = input('month');
        
        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(- 1, '未找到用户');
        }
        
        if (! empty($year)) {
            
            if (! empty($month)) {
                $start_time = mktime(0, 0, 0, $month, 1, $year);
                $end_time = mktime(23, 59, 59, ($month + 1), 0, $year);
                
                $fieldValue = "*,DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') day_time";
                $dateResult = $this->getChartDateSql($start_time, $end_time);
            }
        }
        
        $where = " is_repost = 1 AND uid = {$uid}  AND  create_time >= {$start_time} AND create_time <= {$end_time}";
        
        $dySubQuery = FigureVideoRepost::where($where . " AND way = 1 ")->field($fieldValue)->buildSql();
        $dySecondQuery = Db::table($dySubQuery . ' a')->field("a.day_time,count(1) count")
            ->group('a.day_time')
            ->buildSql();
        
        $dy_data = $this->dateShenjiJoin($dySecondQuery, $dateResult['sql'], "w.date month,IFNULL(a.count,0) count");
        
        $dy_count = array_column($dy_data, 'count');
        $dy_value = array_column($dy_data, 'value');
        
        $ksSubQuery = FigureVideoRepost::where($where . " AND way = 2")->field($fieldValue)->buildSql();
        $ksSecondQuery = Db::table($ksSubQuery . ' a')->field("a.day_time,count(1) count")
            ->group('a.day_time')
            ->buildSql();
        
        $ks_data = $this->dateShenjiJoin($ksSecondQuery, $dateResult['sql'], "w.date month,IFNULL(a.count,0) count");
        
        $ks_count = array_column($ks_data, 'count');
        $ks_value = array_column($ks_data, 'value');
        
        $date = $dateResult['date'];
        foreach ($date as $k => $v) {
            if (! empty($month)) {
                $date[$k] = explode("-", $v)[2] . "日";
            } else {
                $date[$k] = explode("-", $v)[1] . "月";
            }
        }
        
        return result(0, 'success', [
            "date" => $date,
            "dy" => $dy_count,
            "ks" => $ks_count
        ]);
    }

    /**
     * 转发数据
     * http://aigc.weijuyunke.cn/mobile/repost/repostData
     *
     * @param
     *            uid 用户id
     * @param
     *            type 1-DY;2-KS
     * @param
     *            year 年
     * @param
     *            month 月
     *            
     */
    public function repostData()
    {
        try {
            $uid = input('uid');
            $video_id = input('video_id');
            
            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            
            $where = " uid = {$uid} ";
            
            if (! empty(input('way'))) {
                $way = input('way');
                $where .= " AND way = '{$way}'";
            }
            
            if (! empty(input('type'))) {
                $type = input('type');
                $where .= " AND type = '{$type}'";
            }
            
            if (! empty(input('year'))) {
                $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y') = " . input('year');
                
                if (! empty(input('month'))) {
                    $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%m') = " . input('month');
                }
            }
            
            $comment = FigureVideoRepost::where($where)->sum('total_comment');
            $like = FigureVideoRepost::where($where)->sum('total_like');
            $play = FigureVideoRepost::where($where)->sum('total_play');
            $share = FigureVideoRepost::where($where)->sum('total_share');
            
            return result(0, 'success', [
                "play" => $play,
                "like" => $like,
                "comment" => $comment,
                "share" => $share
            ]);
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 日期连接查询
     *
     * @param sql $subQuery
     *            统计sql
     * @param sql $sql
     *            日期sql
     */
    private function dateShenjiJoin($subQuery, $sql, $fields)
    {
        $result = Db::table($subQuery . ' a')->rightJoin([
            $sql => 'w'
        ], "a.day_time=w.date")
            ->order("w.date", "asc")
            ->field($fields)
            ->select()
            ->toArray();
        
        return $result;
    }

    /**
     * 获取图表日期sql
     */
    function getChartDateSql($start_time, $end_time)
    {
        $dateList = array();
        array_push($dateList, date('Y-m-d', $start_time));
        $sql = "(
        SELECT
        '" . date('Y-m-d', $start_time) . "' AS date
        FROM DUAL ";
        
        for ($i = $start_time; $i < $end_time;) {
            
            $date = date('Y-m-d', strtotime("+1 day", $i));
            
            if (strtotime($date) < $end_time) {
                array_push($dateList, $date);
                
                $sql .= "UNION ALL
        SELECT
            '" . $date . "' AS date
        FROM DUAL ";
            }
            
            $i = strtotime("+1 day", $i);
        }
        $sql .= ")";
        return [
            "sql" => $sql,
            "date" => $dateList
        ];
    }





    // 获取 转发的二维码
    public function ClipVideoExhibit()
    {
        $request = $this->request;
        $param = $request->param();
        if ( isset($param['qrcode_type']) && $param['qrcode_type']== 2 ){

            try {
                $uid = input('uid');
                $id = input('id');
                $user = FigureUser::where('id', $uid)->find();
                if (empty($user)) {
                    return result(- 1, '用户不存在');
                }
                $scan_task_video  = new ScanTask();
                $video = $scan_task_video->where([  'id' =>$id ])->find();

                if (empty($video)) {
                    return result(- 1, '任务不存在');
                }
                $douyin_set = sysconfig('forward');
                $domain = request()->domain();
                if ($video['channle_type'] == 1 ) {
                    if ($video['dy_qrcode']){
                        return result(0, 'success', $video['dy_qrcode']);
                    }
                    $url = $domain . "/mobile/index/dy_index?task_id=" . $id .'&qrcode_type='.$param['qrcode_type']."#/?task_id=" . $id.'&qrcode_type='.$param['qrcode_type'];
                }

                if ($video['channle_type'] == 2) {
                    if ($video['ks_qrcode']){
                        return result(0, 'success', $video['ks_qrcode']);
                    }
                    $redirect_uri = urlencode($domain . "/mobile/repost/ksUserAuth?task_id=".$id."&type=3");
                    if ($douyin_set['k_xiaochengxu'] == 1 ){
                        $url = "https://open.kuaishou.com/oauth2/authorize?app_id=" . $douyin_set['k_appid'] . "&response_type=code&scope=user_info,user_video_publish,user_video_info,user_video_mp_plc&redirect_uri=" . $redirect_uri;
                    }else{
                        $url = "https://open.kuaishou.com/oauth2/authorize?app_id=" . $douyin_set['k_appid'] . "&response_type=code&scope=user_info,user_video_publish,user_video_info&redirect_uri=" . $redirect_uri;

                    }



                }
                $qrcode = common_qr_code($url, 'repost');

                if ($video['channle_type'] == 1) {
                    $video->save([
                        'dy_qrcode' => $qrcode
                    ]);
                } elseif ($video['channle_type'] == 2) {
                    $video->save([
                        'ks_qrcode' => $qrcode
                    ]);
                }

                return result(0, 'success', $qrcode);
            } catch (\Exception $e) {
                Log::write("videoExhibit 失败" . json_encode($e->getTrace()), 'info');
                return result(- 1, '操作异常:' . $e->getMessage(), $e->getTrace());
            }
        }else{
            try {
                $way = input('way');
                $uid = input('uid');
                $video_id = input('video_id');
                $user = FigureUser::where('id', $uid)->find();
                if (empty($user)) {
                    return result(- 1, '用户不存在');
                }

                $clipResourceModel = new ClipProject();
                $video = $clipResourceModel->where([  'uid' => $uid, 'id' => $video_id])->find();


                if (empty($video)) {
                    return result(- 1, '视频不存在');
                }

                if ($way == 1 && ! empty($video['dy_qrcode'])) {
                    return result(0, 'success', $video['dy_qrcode']);
                }
                if ($way == 2 && ! empty($video['ks_qrcode'])) {
                    return result(0, 'success', $video['ks_qrcode']);
                }

                $douyin_set = sysconfig('forward');
                $domain = request()->domain();

                if ($way == 1) {
                    $url = $domain . "/mobile/index/dy_index?video_id=" . $video_id . "#/?video_id=" . $video_id;
                } elseif ($way == 2) {
                    $redirect_uri = urlencode($domain . "/mobile/repost/ksUserAuth?&video_id=" . $video_id.'&type= 2 ');
                    $url = "https://open.kuaishou.com/oauth2/authorize?app_id=" . $douyin_set['k_appid'] . "&response_type=code&scope=user_info,user_video_publish,user_video_info&redirect_uri=" . $redirect_uri;
                }

                $qrcode = common_qr_code($url, 'repost');

                if ($way == 1) {
                    $video->save([
                        'dy_qrcode' => $qrcode
                    ]);
                } elseif ($way == 2) {
                    $video->save([
                        'ks_qrcode' => $qrcode
                    ]);
                }

                return result(0, 'success', $qrcode);
            } catch (\Exception $e) {
                Log::write("videoExhibit 失败" . json_encode($e->getTrace()), 'info');
                return result(- 1, '操作异常:' . $e->getMessage(), $e->getTrace());
            }
        }


    }




    /**
     * KS转发
     *
     * @param
     *            uid KS用户id
     * @param
     *            type 1-视频合成 2-视频换脸
     * @param
     *            video_id 视频id
     */
    public function ksClipIssue()
    {

        $request = $this->request;
        $param = $request->param();
        if ( isset($param['qrcode_type']) && $param['qrcode_type']== 2 ){
            $uid = input('uid');
            $user = FigureKsUser::where('id', $uid)->find();
            $id = input('id');
            $ScanTaskModel = new ScanTask();

             $ScanTaskInfo = $ScanTaskModel->where(['id' =>$id ])->find();
            if (empty($ScanTaskInfo)){
                return result(- 1, '任务不存在');
            }
            if ($ScanTaskInfo['status'] == 2){
                return result(- 1, '任务已终止');
            }
            $scanTaskVideoModel  = new ScanTaskVideo();
            $scanTaskVideoList = $scanTaskVideoModel->where(['scan_task' => $id,'status' =>1])->select()->toArray();
            if (empty($scanTaskVideoList)){
                return result(- 1, '视频已全部发布');
            }

            $today = date("Y-m-d");

// 将今天的日期字符串转换为时间戳，默认时间为当日的00:00:00
            $midnightTimestamp = strtotime($today);
            $videoRepostCount = Db::table('wjyk_clip_video_repost')
                ->where(['scan_task'=> $id, 'd_uid' => $uid])
                ->where('create_time', '>', $midnightTimestamp)->count();
            if ($videoRepostCount >= $ScanTaskInfo['release_day_count']){
                return result(- 1, '此任务当日发布数量已上限');
            }
            $clipResourceModel = new ClipProject();
            $video = $clipResourceModel->where([  'id' => $param['video_id']])->find();
            $file = $video['complete_video'];
            $cover = $video['complete_cover'];
            $aiTitle = new FigureAiTitle();
            $titleInfo  = $aiTitle->where(['id' => $param['title_id']])->find();
            $name = $titleInfo['answer'];
            $kuaishou_set = sysconfig('forward');
            $url = "https://open.kuaishou.com/openapi/photo/start_upload?app_id=" . $kuaishou_set['k_appid'] . "&access_token=" . $user['access_token'];

           $arr = wtw_request($url, "{}");
            $arr1 = json_decode($arr, true);

            if ($arr1['result'] == 1) {

                $upload_token = $arr1['upload_token'];
                $endpoint = $arr1['endpoint'];
                $upload_url = "http://{$endpoint}/api/upload?upload_token=" . $upload_token;
                $reply = http_binary($file, $upload_url);

                $data = json_decode($reply, true);
                if ($data['result'] == 1) {
                    $publish_url = "https://open.kuaishou.com/openapi/photo/publish?access_token=" . $user['access_token'] . "&app_id=" . $kuaishou_set['k_appid'] . "&upload_token=" . $upload_token;
                    $send_data = array(
                        'cover' => $cover,
                        'caption' => $name
                    );
                    if (isset($ScanTaskInfo['merchant_product_id']) && $ScanTaskInfo['merchant_product_id']){
                        $send_data['merchant_product_id'] =  $ScanTaskInfo['merchant_product_id'];
                    }

                    $arr2 = wtw_request($publish_url, $send_data);
                    $arr3 = json_decode($arr2, true);
                    if ($arr3['result'] == 1) {
                        $scanTaskVideoModel->where(['three_video_task_id' => $param['video_id']])->update(['status' => 2]);
                        if ($ScanTaskInfo['surplus_num'] == 1){
                            $ScanTaskModel->where(['id' =>$id ])->dec('surplus_num')->update(['status' => 3]);
                        }else{
                            $ScanTaskModel->where(['id' =>$id ])->dec('surplus_num')->update();
                        }

                        Db::table('wjyk_clip_video_repost')->insert(array(
                            'uid' => $video['uid'],
                            'video_id' => $param['video_id'],
                            'way' => 2,
                            'video_url' => $file,
                            'video_cover' => $cover,
                            'k_uid' => $uid,
                            'd_uid' => 0,
                            'title' => $name,
                            'is_repost' => 1,
                            'photo_id' => $arr3['video_info']['photo_id'],
                            'create_time' => time(),
                            'qrcode_type' => $param['qrcode_type'],
                            'scan_task' => $id
                        ));

                        $scan_task_video  = new ScanTaskVideo();
                        $scan_task_video->where(['three_video_task_id'=> $param['video_id']])->update(['status' => 2]);
                        if (  $ScanTaskInfo['anchorUrl']) {
                            $bindData = [
                                'photo_id' => $arr3['video_info']['photo_id']["photo_id"],
                                'plc_mp_app_id' => $ScanTaskInfo["app_id"],
                                'plc_title' => $ScanTaskInfo["app_title"],
                                'plc_mp_path' => $ScanTaskInfo["app_url"],
                                'access_token' => $user['access_token']
                            ];
                            $kuaishouService = new KuaishouService();
                            $kuaishouService->bind($bindData);

                        }

                        return result(0, '发布视频成功');
                    } else {
                        return result(- 1, '发布视频失败', $arr3);
                    }
                }
                return result(- 1, '上传视频失败');
            } else {
                return result(- 1, '获取上传权限失败111');
            }

        }else{
            $uid = input('uid');

            $video_id = input('video_id');

            $user = FigureKsUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }

            $clipResourceModel = new ClipProject();
            $video = $clipResourceModel->where([  'id' => $video_id])->find();

            if (empty($video)) {
                return result(- 1, '视频不存在');
            }

            $file = $video['complete_video'];
            $cover = $video['complete_cover'];
            $name = $video['title'];

            $kuaishou_set = sysconfig('forward');

            $url = "https://open.kuaishou.com/openapi/photo/start_upload?app_id=" . $kuaishou_set['k_appid'] . "&access_token=" . $user['access_token'];
            $arr = wtw_request($url, "{}");
            $arr1 = json_decode($arr, true);

            if ($arr1['result'] == 1) {
                $upload_token = $arr1['upload_token'];
                $endpoint = $arr1['endpoint'];
                $upload_url = "http://{$endpoint}/api/upload?upload_token=" . $upload_token;
                $reply = http_binary($file, $upload_url);

                $data = json_decode($reply, true);
                if ($data['result'] == 1) {
                    $publish_url = "https://open.kuaishou.com/openapi/photo/publish?access_token=" . $user['access_token'] . "&app_id=" . $kuaishou_set['k_appid'] . "&upload_token=" . $upload_token;
                    $send_data = array(
                        'cover' => $cover,
                        'caption' => $name
                    );
                    $arr2 = wtw_request($publish_url, $send_data);
                    $arr3 = json_decode($arr2, true);
                    if ($arr3['result'] == 1) {
                        Db::table('wjyk_clip_video_repost')->insert(array(
                            'uid' => $video['uid'],
                            'video_id' => $video_id,
                            'way' => 2,
                            'video_url' => $file,
                            'video_cover' => $cover,
                            'k_uid' => $uid,
                            'd_uid' => 0,
                            'title' => $name,
                            'is_repost' => 1,
                            'photo_id' => $arr3['video_info']['photo_id'],
                            'create_time' => time()
                        ));



                        return result(0, '发布视频成功');
                    } else {
                        return result(- 1, '发布视频失败', $arr3);
                    }
                }
                return result(- 1, '上传视频失败');
            } else {
                return result(- 1, '获取上传权限失败');
            }
        }
        $ClipProject = new ClipProject();
        $ClipProject->whereIn('id', $row['video_id'])->update(['is_kuaishou' => 3]);
    }

    /**
     * DY转发
     * http://aigc.weijuyunke.cn/mobile/repost/dyIssue
     *
     * @param
     *            uid DY用户id
     * @param
     *            type 1-视频合成 2-视频换脸
     * @param
     *            video_id 视频id
     */
    public function dyClipIssue()
    {
        $request = $this->request;
        $params = $request->param();
        if ( isset($params['qrcode_type']) && $params['qrcode_type']== 2 ){
            $uid = input('uid');
            $user = FigureDyUser::where('id', $uid)->find();

            if (empty($user)) {
                return result(- 1, '用户不存在');
            }
            $id = input('id');
            $ScanTaskModel = new ScanTask();
            $ScanTaskInfo = $ScanTaskModel->where(['id' =>$id ])->find();
            $scanTaskVideoModel  = new ScanTaskVideo();
            $scanTaskVideoList = $scanTaskVideoModel->where(['scan_task' => $id,'status' =>1])->select()->toArray();
            if (empty($scanTaskVideoList)){
                return result(- 1, '视频已全部发布');
            }
            $scanTaskVideoModel->where(['three_video_task_id' => $params['video_id']])->update(['status' => 2]);
            $today = date("Y-m-d");
// 将今天的日期字符串转换为时间戳，默认时间为当日的00:00:00
            $midnightTimestamp = strtotime($today);
            $videoRepostCount = Db::table('wjyk_clip_video_repost')
                ->where(['scan_task'=> $id, 'd_uid' => $uid])
                ->where('create_time', '>', $midnightTimestamp)->count();
            if ($videoRepostCount >= $ScanTaskInfo['release_day_count']){
                return result(- 1, '此任务当日发布数量已上限');
            }
            if (empty($ScanTaskInfo)){
                return result(- 1, '任务不存在');
            }
            if ($ScanTaskInfo['status'] == 2){
                return result(- 1, '任务已终止');
            }
            $clipResourceModel = new ClipProject();
            $video = $clipResourceModel->where([  'id' => $params['video_id']])->find();
            $file = $video['complete_video'];
            $cover = $video['complete_cover'];
            $aiTitle = new FigureAiTitle();
            $titleInfo  = $aiTitle->where(['id' => $params['title_id']])->find();
            $name = $titleInfo['answer'];
            $douyin_set = sysconfig('forward');
            $client_key = $douyin_set['d_key'];
            $client_secret = $douyin_set['d_secret'];
            $client_url = "https://open.douyin.com/oauth/client_token/?grant_type=client_credential&client_key=" . $client_key . "&client_secret=" . $client_secret;
            $client_obj = httpGet($client_url);
            $client_data = json_decode($client_obj, true);
            if ($client_data) {
                $access_token = $client_data['data']['access_token'];
                $ticket_client_url = "https://open.douyin.com/open/getticket/";
                $ticket_client_obj = share_wtw_request($ticket_client_url, null, [
                    'Content-Type: application/json; charset=utf-8',
                    'access-token: ' . $access_token
                ]);
                $ticket_client_obj = \json_decode($ticket_client_obj, true);
                if ($ticket_client_obj && $ticket_client_obj['data']['error_code'] == 0) {
                    // 去获取分享id
                    $share_url = "https://open.douyin.com/share-id/?need_callback=true";
                    $share_data = \json_decode(share_wtw_request($share_url, null, [
                        'Content-Type: application/json; charset=utf-8',
                        'access-token: ' . $access_token
                    ]), true);
                    $nonce_str = createNonceStr();
                    $ticket = $ticket_client_obj['data']['ticket'];
                    $time = (string) time();
                    $param = [
                        "nonce_str" => $nonce_str,
                        "ticket" => $ticket,
                        "timestamp" => $time
                    ];
                    $share_id = "";
                    if ($share_data && $share_data['data']['error_code'] == 0) {
                        $share_id = $share_data['data']['share_id'];
                    } else {
                        return result(- 1, "分享id获取失败");
                        exit();
                    }
                    ksort($param);
                    $string = ToUrlParams($param);
                    $sign = md5($string);
                    if ($ScanTaskInfo['surplus_num'] == 1){
                        $ScanTaskModel->where(['id' =>$id ])->dec('surplus_num')->update(['status' => 3]);
                    }else{
                        $ScanTaskModel->where(['id' =>$id ])->dec('surplus_num')->update();
                    }
                    Db::table('wjyk_clip_video_repost')->insert(array(
                        'uid' => $video['uid'],
                        'video_id' => $params['video_id'],
                        'way' => 1,
                        'd_uid' => $uid,
                        'k_uid' => 0,
                        'share_id' => $share_id,
                        'title' => $name,
                        'video_url' => $file,
                        'video_cover' => $cover,
                        'create_time' => time(),
                        'qrcode_type' => $params['qrcode_type'],
                        'scan_task' => $id
                    ));
                    $scan_task_video  = new ScanTaskVideo();
                    $scan_task_video->where(['three_video_task_id'=> $params['video_id']])->update(['status' => 2]);
                    $result = array(
                        "client_key" => $client_key,
                        "nonce_str" => $nonce_str,
                        "timestamp" => $time,
                        "sign" => $sign,
                        "state" => $share_id,
                        "share_type" => "h5",
                        "share_to_publish" => 1,
                        "video_path" => $file,
                        "app_title"=> $ScanTaskInfo['app_title'],
                        "app_id"=> $ScanTaskInfo['app_id'],
                        "app_url"=>   $ScanTaskInfo['app_url'],
                        "description"=>   $ScanTaskInfo['description'],
                        "poi"=>   $ScanTaskInfo['poi'],
                        "poi_address"=>   $ScanTaskInfo['poi_address'],
                        "sanc_title"=>  $name,
                       'challenges' => $titleInfo['challenges'],
                    );
                    return result(0, 'success', $result);
                } else {
                    return result(- 1, $ticket_client_obj['data']['description']);
                }
            }
        }else{
            $uid = input('uid');
            $video_id = input('video_id');

            $user = FigureDyUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }

            $clipResourceModel = new ClipProject();
            $video = $clipResourceModel->where([  'id' => $video_id])->find();

            if (empty($video)) {
                return result(- 1, '视频不存在');
            }

            $file = $video['complete_video'];
            $cover = $video['complete_cover'];
            $name = $video['title'];

            $douyin_set = sysconfig('forward');
            $client_key = $douyin_set['d_key'];
            $client_secret = $douyin_set['d_secret'];

            $client_url = "https://open.douyin.com/oauth/client_token/?grant_type=client_credential&client_key=" . $client_key . "&client_secret=" . $client_secret;
            $client_obj = httpGet($client_url);
            $client_data = json_decode($client_obj, true);

            if ($client_data) {
                $access_token = $client_data['data']['access_token'];

                $ticket_client_url = "https://open.douyin.com/open/getticket/";
                $ticket_client_obj = share_wtw_request($ticket_client_url, null, [
                    'Content-Type: application/json; charset=utf-8',
                    'access-token: ' . $access_token
                ]);

                $ticket_client_obj = \json_decode($ticket_client_obj, true);
                if ($ticket_client_obj && $ticket_client_obj['data']['error_code'] == 0) {
                    // 去获取分享id

                    $share_url = "https://open.douyin.com/share-id/?need_callback=true";
                    $share_data = \json_decode(share_wtw_request($share_url, null, [
                        'Content-Type: application/json; charset=utf-8',
                        'access-token: ' . $access_token
                    ]), true);

                    $nonce_str = createNonceStr();
                    $ticket = $ticket_client_obj['data']['ticket'];
                    $time = (string) time();
                    $param = [
                        "nonce_str" => $nonce_str,
                        "ticket" => $ticket,
                        "timestamp" => $time
                    ];
                    $share_id = "";
                    if ($share_data && $share_data['data']['error_code'] == 0) {
                        $share_id = $share_data['data']['share_id'];
                    } else {
                        return result(- 1, "分享id获取失败");
                        exit();
                    }

                    ksort($param);

                    $string = ToUrlParams($param);
                    $sign = md5($string);

                    Db::table('wjyk_clip_video_repost')->insert(array(
                        'uid' => $video['uid'],
                        'video_id' => $video_id,
                        'way' => 1,
                        'd_uid' => $uid,
                        'k_uid' => 0,
                        'share_id' => $share_id,
                        'title' => $name,
                        'video_url' => $file,
                        'video_cover' => $cover,
                        'create_time' => time()
                    ));

                    $result = array(
                        "client_key" => $client_key,
                        "nonce_str" => $nonce_str,
                        "timestamp" => $time,
                        "sign" => $sign,
                        "state" => $share_id,
                        "share_type" => "h5",
                        "share_to_publish" => 1,
                        "video_path" => $file
                    );
                    return result(0, 'success', $result);
                } else {
                    return result(- 1, $ticket_client_obj['data']['description']);
                }
            }
        }

    }

    /**
     * 转发记录
     * http://aigc.weijuyunke.cn/mobile/repost/repostClipList
     *
     * @param
     *            uid 用户id
     * @param
     *            video_id 视频id
     * @param
     *            way 1-DY;2-KS


     * @param
     *            year 年
     * @param
     *            month 月
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function repostClipList()
    {
        try {
            $request = $this->request;
            $param = $request->param();
            $uid = input('uid');
           $video_id = input('video_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }

            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));

            $where = " uid = {$uid}  AND is_repost = 1 ";


            if (! empty(input('way'))) {
                $way = input('way');
                $where .= " AND way = '{$way}'";
            }
            if (isset($param['video_id']) &&  ! empty(input('video_id'))) {
                $video_id = input('video_id');
                $where .= " AND video_id = '{$video_id}'";
            }
            if (isset($param['scan_task']) &&  ! empty(input('scan_task'))) {
                $scan_task = input('scan_task');
                $where .= " AND scan_task = '{$scan_task}'";
            }


            if (isset($param['year']) && ! empty(input('year'))) {
                $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y') = " . input('year');

                if (! empty(input('month'))) {
                    $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%m') = " . input('month');
                }
            }

            if (isset($param['day']) &&  ! empty(input('day'))) {
                $day = input('day');
                $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$day}'";
            }

            $total = ClipVideoRepost::where($where)->count();
            if ($total) {
                $list = ClipVideoRepost::where($where)->order('create_time', 'desc')
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();

                foreach ($list as $key => $value) {

                    if ($value['way'] == 1) {
                        $user = FigureDyUser::where('id', $value['d_uid'])->find();
                    } elseif ($value['way'] == 2) {
                        $user = FigureKsUser::where('id', $value['k_uid'])->find();
                    }

                    $list[$key]['nickname'] = isset($user['nickname']) ? $user['nickname'] : '';
                    $list[$key]['avatar'] = isset($user['avatar']) ? $user['avatar'] : '';
                }
            } else {
                $list = array();
            }

            $totalPage = ceil($total / $psize);

            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 转发统计
     * http://aigc.weijuyunke.cn/mobile/repost/dataStatis
     *
     * @param
     *            uid 用户id
     * @param
     *            type 1-视频合成 2-视频换脸 非必传
     * @param
     *            video_id 视频id 非必传
     */
    public function dataClipStatis()
    {
        $uid = input('uid');

        $user = FigureUser::where('id', $uid)->find();

        if (empty($user)) {
            return result(- 1, '未找到用户');
        }

        $where = " uid = {$uid} ";


        if (! empty(input('video_id'))) {
            $video_id = input('video_id');
            $where .= " AND video_id = '{$video_id}'";
        }

        $dyWhere = $where . " AND way = 1 ";

        $dy_comment = ClipVideoRepost::where($dyWhere)->sum('total_comment');
        $dy_like = ClipVideoRepost::where($dyWhere)->sum('total_like');
        $dy_play = ClipVideoRepost::where($dyWhere)->sum('total_play');
        $dy_share = ClipVideoRepost::where($dyWhere)->sum('total_share');

        $ksWhere = $where . " AND way = 2 ";

        $ks_comment = ClipVideoRepost::where($ksWhere)->sum('total_comment');
        $ks_like = ClipVideoRepost::where($ksWhere)->sum('total_like');
        $ks_play = ClipVideoRepost::where($ksWhere)->sum('total_play');
        $ks_share = ClipVideoRepost::where($ksWhere)->sum('total_share');

        $result['dy_comment'] = empty($dy_comment) ? 0 : $dy_comment;
        $result['dy_like'] = empty($dy_like) ? 0 : $dy_like;
        $result['dy_play'] = empty($dy_play) ? 0 : $dy_play;
        $result['dy_share'] = empty($dy_share) ? 0 : $dy_share;
        $result['ks_comment'] = empty($ks_comment) ? 0 : $ks_comment;
        $result['ks_like'] = empty($ks_like) ? 0 : $ks_like;
        $result['ks_play'] = empty($ks_play) ? 0 : $ks_play;
        $result['ks_share'] = empty($ks_share) ? 0 : $ks_share;

        return result(0, 'success', $result);
    }

    /**
     * 作品统计
     * http://aigc.weijuyunke.cn/mobile/repost/workStatis
     *
     * @param
     *            uid 用户id
     * @param
     *            year 年
     * @param
     *            month 月
     */
    public function workClipStatis()
    {
        $uid = input('uid');
        $year = input('year');
        $month = input('month');

        $user = FigureUser::where('id', $uid)->find();
        if (empty($user)) {
            return result(- 1, '未找到用户');
        }

        if (! empty($year)) {

            if (! empty($month)) {
                $start_time = mktime(0, 0, 0, $month, 1, $year);
                $end_time = mktime(23, 59, 59, ($month + 1), 0, $year);

                $fieldValue = "*,DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') day_time";
                $dateResult = $this->getChartDateSql($start_time, $end_time);
            }
        }
        $where = " is_repost = 1 AND uid = {$uid} AND  qrcode_type = 1 AND  create_time >= {$start_time} AND create_time <= {$end_time}";
        $dySubQuery = ClipVideoRepost::where($where . " AND way = 1 ")->field($fieldValue)->buildSql();
        $dySecondQuery = Db::table($dySubQuery . ' a')->field("a.day_time,count(1) count")
            ->group('a.day_time')
            ->buildSql();

        $dy_data = $this->dateShenjiJoin($dySecondQuery, $dateResult['sql'], "w.date month,IFNULL(a.count,0) count");

        $dy_count = array_column($dy_data, 'count');
        $dy_value = array_column($dy_data, 'value');

        $ksSubQuery = FigureVideoRepost::where($where . " AND way = 2")->field($fieldValue)->buildSql();
        $ksSecondQuery = Db::table($ksSubQuery . ' a')->field("a.day_time,count(1) count")
            ->group('a.day_time')
            ->buildSql();

        $ks_data = $this->dateShenjiJoin($ksSecondQuery, $dateResult['sql'], "w.date month,IFNULL(a.count,0) count");

        $ks_count = array_column($ks_data, 'count');
        $ks_value = array_column($ks_data, 'value');

        $date = $dateResult['date'];
        foreach ($date as $k => $v) {
            if (! empty($month)) {
                $date[$k] = explode("-", $v)[2] . "日";
            } else {
                $date[$k] = explode("-", $v)[1] . "月";
            }
        }

        return result(0, 'success', [
            "date" => $date,
            "dy" => $dy_count,
            "ks" => $ks_count
        ]);
    }

    /**
     * 转发数据
     * http://aigc.weijuyunke.cn/mobile/repost/repostData
     *
     * @param
     *            uid 用户id
     * @param
     *            type 1-DY;2-KS
     * @param
     *            year 年
     * @param
     *            month 月
     *
     */
    public function repostClipData()
    {
        try {
            $uid = input('uid');
            $video_id = input('video_id');

            $user = FigureUser::where('id', $uid)->find();
            if (empty($user)) {
                return result(- 1, '用户不存在');
            }

            $where = " uid = {$uid} ";

            if (! empty(input('way'))) {
                $way = input('way');
                $where .= " AND way = '{$way}'";
            }



            if (! empty(input('year'))) {
                $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y') = " . input('year');

                if (! empty(input('month'))) {
                    $where .= " AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%m') = " . input('month');
                }
            }

            $comment = ClipVideoRepost::where($where)->sum('total_comment');
            $like = ClipVideoRepost::where($where)->sum('total_like');
            $play = ClipVideoRepost::where($where)->sum('total_play');
            $share = ClipVideoRepost::where($where)->sum('total_share');

            return result(0, 'success', [
                "play" => $play,
                "like" => $like,
                "comment" => $comment,
                "share" => $share
            ]);
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public function clipVideoInfo(){
        $request = $this->request;
        $param = $request->param();
        $id = input('id');
        if ( isset($param['qrcode_type']) && $param['qrcode_type']== 2 ){
            $scan_task_Title = new ScanTaskTitle();
            $scanTaskVideoTitle = $scan_task_Title->where(['scan_task' => $id])->select()->toArray();
            $randomTitleKey = array_rand($scanTaskVideoTitle);
            $randomTitleArray = $scanTaskVideoTitle[$randomTitleKey];
            $FigureAiTitle  = new FigureAiTitle();
            $FigureAiTitleInfo =  $FigureAiTitle->where(['id' => $randomTitleArray['title_id']])->find();
            $ScanTaskModel = new ScanTask();
            $scanTaskVideoModel  = new ScanTaskVideo();
            $ScanTaskInfo = $ScanTaskModel->where(['id' =>$id ])->find();
            if ($ScanTaskInfo['status'] == 2){
                return result(- 1, '任务已终止');
            }
            if (empty($ScanTaskInfo)){
                return result(- 1, '任务不存在');
            }
            $scanTaskVideoList = $scanTaskVideoModel->where(['scan_task' => $id,'status' =>1])->select()->toArray();
            if (empty($scanTaskVideoList)){
                return result(- 1, '视频已全部发布');
            }
            $randomKey = array_rand($scanTaskVideoList);
            // 使用键名从数组中获取对应的子数组
            $randomSubArray = $scanTaskVideoList[$randomKey];
            //$scanTaskVideoModel->where(['scan_task' => $randomSubArray['id']])->update(['status' => 2]);
            $clipResourceModel = new ClipProject();
            $video = $clipResourceModel->where([  'id' => $randomSubArray['three_video_task_id']])->find();
            $video['sanc_title'] =$FigureAiTitleInfo['answer'];
            $video['title_id'] =$FigureAiTitleInfo['id'];
            $video['poi']  =$ScanTaskInfo['poi'];
            $video['challenges']  =$FigureAiTitleInfo['challenges'];
            $video['poi_address']  =$ScanTaskInfo['poi_address'];
            return result(0, 'success',$video);
        }else{
            $video_id = input('video_id');
            $clipResourceModel = new ClipProject();
            $video = $clipResourceModel->where([ 'id' => $video_id])->find();
            return result(0, 'success',$video);
        }
    }

    public function commentList(){
        $id = input('video_id');
        $RepostCommentModel =  new RepostComment();
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        $total = $RepostCommentModel->where(['repost_id' => $id ])->count();
        $list = $RepostCommentModel->where(['repost_id' => $id ])->order('create_time', 'desc')
            ->limit(($pindex - 1) * $psize, $psize)
            ->select();
        $totalPage = ceil($total / $psize);
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    public function replyComment(){
        $request = $this->request;
        $param = $request->param();
        $FigureDyUser  = new FigureDyUser();
        $clipVideoRepostModel   = new ClipVideoRepost();
        $RepostComment  = new RepostComment();
        $repostComentInfo  = $RepostComment->where(['id'=> $param['id']])->find();
        $clipVideoRepostInfo = $clipVideoRepostModel->where(['id'=> $repostComentInfo['repost_id']])->find();
        $douyingUid =$FigureDyUser->where(['id' => $clipVideoRepostInfo['d_uid']])->find();
        $data['item_id']  = urlencode($clipVideoRepostInfo['item_id']);
        $data['content']  = $param['content'];
        $data['comment_id']  = $clipVideoRepostInfo['comment_id'];
        $url = "https://open.douyin.com/api/apps/v1/item/reply_comment/?open_id=" . $douyingUid['openid'] ;
        $arr = $this->forward_video_request($url, $data, $douyingUid['access_token']);
        $arr1 = json_decode($arr, true);
        if ($arr1['data']['error_code'] == 0) {
            return result(0, '回复成功');
        }else{
            return result(-1, '回复失败');
        }
    }

    function forward_video_request($url, $data = null, $token = null)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        if ($data != null) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        }

        $header = array(
            'Content-Type: application/json'
        );

        if ($token != null) {
            array_push($header, 'access-token:  ' . $token);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 类型为json
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 300); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $info = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            // echo 'Errno:'.curl_getinfo($curl);//捕抓异常
            // dump(curl_getinfo($curl));
        }

        return $info;
    }

    public function scanTaskStatis()
    {
        $request = $this->request;
        $param = $request->param();
        $ScanTaskModel =  new ScanTask();
        $where =[];
        $taskCountwhere =[];

        $taskCount = $ScanTaskModel->where(['uid' =>$param['uid'] ])->where($taskCountwhere)->count();
        $taskDouyinCount = $ScanTaskModel->where(['uid' =>$param['uid'],'channle_type' => 1 ])->count();
        $taskKuaishouCount = $ScanTaskModel->where(['uid' =>$param['uid'] ,'channle_type' => 2])->count();


        $where['uid'] = $param['uid'];
        if (isset($param['scan_task']) && $param['scan_task'] ){
            $where['scan_task'] =  $param['scan_task'];
            $taskCountwhere['id'] =  $param['scan_task'];
        }
        if (! empty(input('video_id'))) {
            $video_id = input('video_id');
            $where['video_id'] = $video_id;
        }
        $where['qrcode_type'] = 2;
        $comment = ClipVideoRepost::where($where)->sum('total_comment');
        $like = ClipVideoRepost::where($where)->sum('total_like');
        $play = ClipVideoRepost::where($where)->sum('total_play');
        $share = ClipVideoRepost::where($where)->sum('total_share');
        $releaseCount  =  ClipVideoRepost::where($where)->count();
        $result['comment'] = empty($comment) ? 0 : $comment;
        $result['like'] = empty($like) ? 0 : $like;
        $result['play'] = empty($play) ? 0 : $play;
        $result['release_count'] = empty($releaseCount) ? 0 : $releaseCount;
        $result['share'] = empty($share) ? 0 : $share;
        $result['task_douyin_count'] = empty($taskDouyinCount) ? 0 : $taskDouyinCount;
        $result['task_count'] = empty($taskCount) ? 0 : $taskCount;
        $result['task_kuaishou_count'] = empty($taskKuaishouCount ) ? 0 : $taskKuaishouCount ;
        return result(0, 'success', $result);
    }

    public function sancTitle(){
        $request = $this->request;
        $param = $request->param();
        $id = input('id');
        $scan_task_Title = new ScanTaskTitle();
        $scanTaskVideoTitle = $scan_task_Title->where(['scan_task' => $id])->select()->toArray();
        $randomTitleKey = array_rand($scanTaskVideoTitle);
        $randomTitleArray = $scanTaskVideoTitle[$randomTitleKey];
        $FigureAiTitle  = new FigureAiTitle();
        $FigureAiTitleInfo =  $FigureAiTitle->where(['id' => $randomTitleArray['title_id']])->find();
        $video['sanc_title'] =$FigureAiTitleInfo['answer'];
        $video['challenges'] =$FigureAiTitleInfo['challenges'];
        $video['title_id'] =$FigureAiTitleInfo['id'];
        return result(0, 'success',$video);
    }

}